<?php
use PFT\Tool\Tools;
use PFT\PriceGroup;
use PFT\Db;

if (!$_SESSION['sid']) {
	exit(json_encode(array('status' => -1,'msg' => '请先登陆')));
}

include 'class/Tools.class.php';
include 'class/PriceGroup.class.php';
include '/var/www/html/new/d/module/common/Db.class.php';
$db_conf = include '/var/www/html/new/d/module/common/db.conf.php';
Db::ConnectRef();

$soap_client = new SoapClient(null,array(
	"location" => "http://localhost/open/openService/pft_insideMX.php",
	"uri" => "www.16u.com?ac_16u=16ucom|pw_16u=c33367701511b4f6020ec61ded352059|auth_16u=true")
);

$request = Tools::deepRemoveXss($_REQUEST);
$sid = $_SESSION['sid'];
//登陆判断
// $request['ctype'] = array('电商','其他');
switch ($request['act']) {
	case 'test':
		PriceGroup::test();
		break;
	//获取分销商分组列表
	case 'get_distributors':
		//关键字查询
		if (isset($request['keyword']) && $request['keyword']) {
			$keyword = $request['keyword'];
			$key_condition = " and (instr(m.dname,'".$keyword."') 
								or instr(m.cname,'".$keyword."') 
								or m.account='".$keyword."' 
								or m.mobile='".$keyword."') ";
		}
		//这些条件需要取pft_member_extinfo表
		if (isset($request['city']) || isset($request['province']) || isset($request['ctype'])) {
			$extend_table = " left join pft_member_extinfo as e on e.fid=m.id ";
			if ($request['ctype']) {
				// var_dump($request['ctype']);die;
				$request['ctype'] = explode(',', $request['ctype']);
				$ctype_condition = ' and (';
				foreach ($request['ctype'] as $type) {
					$ctype_condition .= " instr(e.com_type, '{$type}') or";
				}
				$ctype_condition = rtrim($ctype_condition, 'or') . ') ';
			}
			if ($request['province']) {
				$province_condition = " and e.province={$request['province']} ";
			}
			if ($request['city']) {
				$city_condition = " and e.city={$request['city']} ";
			}
		}
		
		$sql = "select m.id,m.dname,m.cname,m.account,m.mobile,r.son_id_type,r.ship_type 
			from pft_member as m left join pft_member_relationship as r  
			on m.id = r.son_id {$extend_table} 
			where m.status in (0,3) and r.status=0 and r.parent_id={$sid} and r.ship_type=0 
			and length(m.account)=6 and r.son_id<>{$sid} 
			{$key_condition} {$ctype_condition} {$province_condition} {$city_condition}";
		// echo $sql;die;
		$distributors = Db::fetchAll($sql);
		// var_dump($distributors);die;
		if (count($distributors) == 0) {
			exit(json_encode(array('status' => 1,'data' => array())));
		}
		//获取用户的账户余额和授信额度
		foreach ($distributors as $key => $distributor) {
			//供应商余额
			$remain = $soap_client->PFT_Member_Fund($distributor['id'], 1, $sid);
			$remain = simplexml_load_string($remain);
			$distributors[$key]['remain'] = (int)$remain->Rec->UUkmoney / 100;
			//供应商额度
			$limit = $soap_client->PFT_Member_Fund($distributor['id'], 2, $sid);
			$limit = simplexml_load_string($limit);
			$distributors[$key]['limit'] = (int)$limit->Rec->UUbasecredit / 100;
			$distributors[$key]['total'] = $distributors[$key]['remain'] + $distributors[$key]['limit'];
		}

		$did_arr = $new_distributors = array();
		foreach ($distributors as $distributor) {
			$did_arr[] = $distributor['id'];
			$new_distributors[$distributor['id']] = $distributor;
		}

		//将分销商按分组分类
		$own_groups = PriceGroup::getGroupsBySid($sid);
		$groups = array();
		foreach ($own_groups as $group) {
			$group_did_arr = explode(',', $group['dids']);
			$group_members = array();
			foreach ($group_did_arr as $did) {
				if (!in_array($did, $did_arr))
					continue;
				$group_members[] = $new_distributors[$did];
			}
			$groups[] = array(
				'group_id' => $group['id'],
				'group_name' => $group['name'],
				'group_members' => $group_members
			);
			$did_arr = array_diff($did_arr, $group_did_arr);
		}
		//未经分组的分销商，默认为“未分组”
		$unjoin_members = array();
		// $groups['total'] = ;
		foreach ($did_arr as $did) {
			$unjoin_members[] = $new_distributors[$did];
		}
		$page = $request['page'] ?: 1;
		$page_size = $request['page_size'] ?: 10;
		$iterator = new ArrayIterator($unjoin_members);
		$limits = new LimitIterator($iterator, ($page - 1) * $page_size, $page_size);
		$unjoin_members = array();
		foreach ($limits as $limit) {
		    $unjoin_members[] = $limit;
		}
		$groups[] = array(
			'group_id' => 0,
			'group_name' => '未分组',
			'group_members' => $unjoin_members
		);
		// var_dump($groups);die;
		//剩余的人为处于未分组状态
		exit(json_encode(
			array('status' => 1,
			 	'total_page' => ceil(count($did_arr) / $page_size),
			 	'current_page' => $page,
			  	'data' => $groups
			  )
			)
		);
		break;

	case 'add_new_group':
		if (!isset($request['group_name']) || !$request['group_name']) {
			$status = 0;
			$info = '分组名称不能为空';
		} else {
			if (PriceGroup::addNewGroup($sid, $request['group_name'])) {
			 	$status = 1;
				$info = '新建分组成功';
			} else {
				$status = 0;
				$info = '新建分组失败';
			}
		}
		exit(json_encode(array('status' => $status,'msg' => $info)));
		break;
		
	case 'move_group':
		if (!($request['did'])) {
			$status = 0;
			$info = '参数错误';
		} else {
			if ($request['to']) {
				$to_info = PriceGroup::getGroupById($request['to'], $sid);
				if ($to_info) {
					$default_inc = json_decode($to_info['default_inc'],true);
					if (!$default_inc) {
						if (!isset($request['confirm'])) {
							exit(json_encode(array('status' => -2,'msg' => '该组尚未配置价格')));
						}
					}
				}
			}
			if ($request['source'] == $request['to']) {
				exit(json_encode(array('status' => 1,'msg' => '移动成功')));
			}
			if (PriceGroup::moveGroup($request['did'], $request['source'], $request['to'], $sid)) {
				$status = 1;
				$info = '移动成功';
			} else {
				$status = 0;
				$info = '移动失败';
			}
		}
		exit(json_encode(array('status' => $status,'msg' => $info)));
		break;
	case 'join_group':
		if (!($request['did'] && $request['gid'])) {
			$status = 0;
			$info = '参数错误';
		} else {
			if (PriceGroup::joinGroup($request['gid'], $request['did'], $sid)) {
				$status = 1;
				$info = '加入成功';
			} else {
				$status = 0;
				$info = '加入失败';
			}
		}
		exit(json_encode(array('status' => $status,'msg' => $info)));
		break;
	case 'update_group':
		if (!isset($request['gid'],$request['group_name'])||!$request['gid']||!$request['group_name'])  {
			$status = 0;
			$info = '参数错误';
		} else {
			if (PriceGroup::hasGroupExists($sid, $request['group_name'])) {
				$status = 0;
				$info = '该分组已经存在';
			} else {
				if (PriceGroup::updateGroup($request['gid'], $request['group_name'], $sid)) {
					$status = 1;
					$info = '更新分组名称成功';
				} else {
					$status = 0;
					$info = '更新失败';
				}
			}
		}
		exit(json_encode(array('status' => $status,'msg' => $info)));
		break;
	case 'delete_group':
		if (!isset($request['gid']) && !$request['gid']) {
			$status = 0;
			$info = '参数错误';
		} else {
			if (PriceGroup::deleteGroup($sid, $request['gid'])) {
				$status = 1;
				$info = '删除成功';
			} else {
				$status = 1;
				$info = '删除失败';
			}
		}
		exit(json_encode(array('status' => $status,'msg' => $info)));
		break;
	default:
		exit(json_encode(array('status' => 0,'msg' => 'bad request')));;
}